package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"io/ioutil"
	"net/http"
	"src/gRPC/gw2rpc/conf"
	gw "src/gRPC/proto"
	//"src/golearn/s9/tools"
	"time"
)

func main() {

	//tools.PrintHr("testRpc")

	fmt.Println("testRpc")
	testRpc()

	//tools.PrintHr("testHttp")

	fmt.Println("testHttp")
	testHttp()

}

func testHttp() {

	var addrHttp = conf.SERVER_ADDR_HTTP
	resp, err := http.Get("http://" + addrHttp + "/v1/dog/zs2")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
}

func testRpc() {

	//1.链接gRPC服务器
	var addr = conf.SERVER_ADDR_RPC
	conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		fmt.Println("client connect fail")
	}

	defer conn.Close()

	fmt.Println("client connect ok:", addr)

	//2.实例化gRPC客户端
	var client = gw.NewDogServiceClient(conn)

	//3.组装请求参数
	var req = &gw.DogRequest{
		Name: "zs",
	}

	//4.调用接口
	//添加超时设置
	ctx, _ := context.WithTimeout(context.Background(), time.Second*3)
	resp, err := client.GetInfo(ctx, req)

	if err != nil {
		fmt.Println("rpc call fail", err)
	}
	fmt.Printf("%#v \n", resp)

	fmt.Printf("dog id=%d \n", resp.GetId())
	fmt.Printf("dog name=%s \n", resp.GetName())
}
